package com.xuexuehai.bkm.core.configuration.config;

import com.xuexuehai.bkm.core.configuration.interceptor.AuthorityInterceptor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/9/11 1:40 下午
 */
@Configuration
public class WebmvcConfig implements WebMvcConfigurer {

    private final static ThreadLocal<SimpleDateFormat> LOCAL = new ThreadLocal<>();


    @Override
    public void addFormatters(FormatterRegistry registry) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        if(LOCAL.get() == null){
            LOCAL.set(simpleDateFormat);
        }
        registry.addConverter(new Converter<String, Date>() {

            @Override
            @SneakyThrows
            public Date convert(String s) {
                SimpleDateFormat sdf = LOCAL.get();

                Date date = sdf.parse(s);
                return date;
            }
        });
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedMethods("PUT","GET","DELETE","POST")
                .maxAge(60*60);
    }

    @Bean
    public AuthorityInterceptor getAuthorityInterceptor(){
        return new AuthorityInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getAuthorityInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/admin/login")
                ;
    }
}
